<template>
    <div class="content">
        <!-- 顶部区域 -->
         <introParagraph></introParagraph>
        <!-- 默认问题区域 -->
        <defultQuestion @questionClick="handleQuestionClick"></defultQuestion>
        <!-- 用户发送消息区域 -->
        <chatMessage ref="chatMessageRef"></chatMessage>
        <!-- 底部输入区域 -->
        <inputArea></inputArea>
    </div>
</template>

<script setup lang="ts">
import { ref, provide, onMounted } from 'vue'
import introParagraph from '@/page/component/introParagraph.vue'
import defultQuestion from '@/page/component/defultQuestion.vue'
import chatMessage from '@/page/component/chatMessage.vue'
import inputArea from '@/page/component/inputArea.vue'
import { sendChatMessageStream } from '@/api/chatService'

// 获取chatMessage组件实例
const chatMessageRef = ref<InstanceType<typeof chatMessage>>();

// 提供依赖注入，使inputArea组件能够访问chatMessage组件的方法
provide('chatMessageRef', {
  addUserMessage: (content: string, images?: string[]) => chatMessageRef.value?.addUserMessage(content, images),
  addAssistantMessage: (content: string, data?: any) => chatMessageRef.value?.addAssistantMessage(content, data),
  setLoading: (loading: boolean) => chatMessageRef.value?.setLoading(loading),
  updateAssistantMessage: (index: number, content: string, data?: any) => chatMessageRef.value?.updateAssistantMessage(index, content, data),
  getMessageCount: () => chatMessageRef.value?.getMessageCount() || 0
});

// 处理默认问题点击
const handleQuestionClick = async (question: string) => {
  // 添加用户消息到聊天记录
  chatMessageRef.value?.addUserMessage(question)
  chatMessageRef.value?.setLoading(true)
  
  let assistantMessageIndex = -1
  let accumulatedContent = ''
  
  try {
    // 构建消息格式
    const messages = [{ role: 'user', content: question }]
    
    // 使用流式API发送消息
    sendChatMessageStream(
      messages,
      // 处理每个数据块
      (chunk) => {
        if (chunk.type === 'text' && chunk.content) {
          accumulatedContent += chunk.content
          
          // 如果是第一条文本内容，添加一个新的助手消息
          if (assistantMessageIndex === -1) {
            chatMessageRef.value?.addAssistantMessage(accumulatedContent)
            assistantMessageIndex = (chatMessageRef.value?.getMessageCount() || 1) - 1
          } else {
            // 更新现有的助手消息
            chatMessageRef.value?.updateAssistantMessage(assistantMessageIndex, accumulatedContent)
          }
        } else if (chunk.type === 'tool_result') {
          // 处理工具调用结果
          const toolChunk = chunk as any; // 临时类型断言
          const toolData = {
            tool: toolChunk.tool,
            success: toolChunk.success,
            data: toolChunk.data,
            message: toolChunk.message
          }
          
          // 添加工具调用结果消息
          chatMessageRef.value?.addAssistantMessage('', toolData)
        }
      },
      // 完成回调
      () => {
        chatMessageRef.value?.setLoading(false)
      },
      // 错误回调
      (error) => {
        chatMessageRef.value?.setLoading(false)
        if (assistantMessageIndex === -1) {
          chatMessageRef.value?.addAssistantMessage(error || '抱歉，发送失败，请稍后重试')
        } else {
          chatMessageRef.value?.updateAssistantMessage(assistantMessageIndex, error || '抱歉，消息发送过程中出现错误')
        }
      }
    )
  } catch (error: any) {
    chatMessageRef.value?.setLoading(false)
    chatMessageRef.value?.addAssistantMessage(error.message || '网络错误，请稍后重试')
  }
}

// 组件挂载后确保引用已绑定
onMounted(() => {
  console.log('Chat message component ref:', chatMessageRef.value);
});
</script>

<style scoped lang="less"> 
  .content{
    padding: 0 15px;
    height: 100vh;
    overflow-y: auto;
    padding-bottom: 120px; /* 为底部输入区域留出空间 */
  }
  
  /* 确保聊天消息区域可以滚动 */
  .content :deep(.chat-message) {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
  }
</style>
